<?php
/**
 *	@name		商品拍卖
 *	@author		Jeffery
 *	@qq			1017756891
 *	@email		1017756891@qq.com
 *	@website	http://www.iweitao.net
**/

require_once "core.php";

class threadplugin_iweitao_paipai extends safe_weitao_plugin_iweitao_paipai{

	var $name = "商品拍卖";	//特殊主题名称
	var $iconfile = '';		//特殊主题图标
	var $buttontext = "竞拍商品";	//发布按钮文字
	
	/**
	 * [newthread 发布拍卖]
	 * @param  [type] $fid [description]
	 * @return [type]      [description]
	 */
	function newthread($fid) {
		//发布新的帖子，显示表单
		global $_G,$groups,$types,$mades;
		// v认证检测
		authenticate_paipai();
		// 获得拍卖模式 
		$thread_type = null;
		//判断是否在允许的用户组内
		if(in_array($_G['groupid'],$groups)) { 
			include template("iweitao_paipai:newthread");
			return $return;
		} else {
			showmessage("您所在的用户组不允许使用该功能");
		}
	}

	function newthread_submit($fid) {
		//提交数据，对数据进行过滤操作
		authenticate_paipai();
		$price = $this->_post('price',1);
		$add_price = $this->_post('add_price',1);
		$title = $this->_post('title');
		$date_start = $this->_post('date_start');
		$date_end = $this->_post('date_end');
		$date_start = strtotime($date_start);
		$date_end = strtotime($date_end);
		if ($date_end <= $date_start) {
			showmessage("结束时间不能小于开始时间");
		}
		$imgs = array();
		for($a = 1; $a <= 5; $a++) {
			if($this->_post('auctionaid_url'.$a) != '') {
				$imgs[$a] = "GETIMG";
			}
			
		}
		if(!in_array("GETIMG",$imgs)) {
			showmessage('必须要上传一张图片');
		}
		if(!is_numeric($price) || !is_numeric($add_price)) {
			showmessage('价格必须为数字'); //您的价格必须为数字
		}
		if(empty($title)) {
			showmessage("商品名称不能为空");
		}
	}

	function newthread_submit_end($fid, $tid) {
		//验证成功，保存数据
		global $_G;
		// 生成唯一编号
		$serial_num = substr(md5(serialize(time())),-4) . date(ymd);
		$price = $this->_post('price',1);
		$origin_price = $this->_post('price',1);
		$add_price = $this->_post('add_price',1);
		$title = $this->_post('title');
		$date_start = $this->_post('date_start');
		$date_end = $this->_post('date_end');
		$pub_time = time();
		$date_start = strtotime($date_start);
		$date_end = strtotime($date_end);
		// $type = $this->_post('type');	//类型，废除
		// 制作材料
		$type_made = $this->_post('type_made');	
		$send = $this->_post('send');	// 送货方式	废除
		$thread_type = $this->_post('thread_type'); // 拍卖模式，只有default 默认模式
		for($a = 1; $a <= 5; $a++) {
			if($a == 1) {
				convertunusedattach($this->_post("auctionaid1"),$tid,1);
				$auctionaid_url1 = $this->_post('auctionaid_url'.$a);
			} else if($a == 2) {
				convertunusedattach($this->_post("auctionaid2"),$tid,1);
				$auctionaid_url2 = $this->_post('auctionaid_url'.$a);
			} else if($a == 3) {
				convertunusedattach($this->_post("auctionaid3"),$tid,1);
				$auctionaid_url3 = $this->_post('auctionaid_url'.$a);
			} else if($a == 4) {
				convertunusedattach($this->_post("auctionaid4"),$tid,1);
				$auctionaid_url4 = $this->_post('auctionaid_url'.$a);
			} else if($a == 5) {
				convertunusedattach($this->_post("auctionaid5"),$tid,1);
				$auctionaid_url5 = $this->_post('auctionaid_url'.$a);
			}
		}

		// 字段
		$fields = "`serial_num`,`tid`,`uid`,`orderid`,`username`,`made`,`title`,`price`,`add_price`,`origin_price`,`focus`,`focus2`,`focus3`,`focus4`,`focus5`,`pub_time`,`date_start`,`date_end`,`identify`,`status`,`freeze`";

		// 数据
		$values = "'$serial_num','$tid','".$_G['uid']."','','".$_G['username']."','$type_made','$title',";
		$values2 = "'$price','$add_price','$origin_price',";
		$values3 = "'$auctionaid_url1','$auctionaid_url2','$auctionaid_url3','$auctionaid_url4','$auctionaid_url5','$pub_time','$date_start','$date_end','$thread_type','1',0";
		$str = $values.$values2.$values3;
		
		// 添加拍卖商品
		$re = DB::query("INSERT INTO `".DB::table("paipai_goods")."`($fields) VALUES($str)");
		// 修改帖子message值
		// $message = chr(0).chr(0).chr(0).'iweitao_paipai';
		$message = '拍卖商品' . $re;
		DB::query("UPDATE ".DB::table("forum_post")." SET message = '".$message."' WHERE pid = '$pid'");
	}

	function editpost($fid, $tid) {
		
	}

	function editpost_submit($fid, $tid) {
		
	}

	function editpost_submit_end($fid, $tid) {
		
	}

	function newreply_submit_end($fid, $tid) {

	}

	function viewthread($tid) { //查看贴子，调用数据模板
		global $_G;
		// var_dump($_G['uid']);
		global $admingroup;
		authenticate_paipai();
		// 允许管理员查看
		$this->check_goods_status($tid,'message',TRUE);
		// 出价列表信息
		$detail = $this->getorderdetail($tid);
		//商品信息
		$array = $this->getgoodsdetail_by_tid($tid);

		// 最高出价
		$max = $this->getgoods_maxbuy_by_tid($tid);
		// 上传图片压入数组
		$focus = array(
			$array['focus'],
			$array['focus2'],
			$array['focus3'],
			$array['focus4'],
			$array['focus5'],
		);

		
		// var_dump($array['identify']);
		// 默认模式
		$thread_type = $this->get_thread_type($array['identify']);
	
		// 载入模板
		include template("iweitao_paipai:viewthread");
		return $return;
	}

	// 根据tid获得商品和竞拍成功订单信息
	public function get_goods_buy_order_by_tid($tid){
		$sql = "SELECT a.`uid`,a.`gid`,a.`tid`,a.`title`,a.`date_start`,a.`date_end`,a.`price`,a.`origin_price`,a.`identify`,a.`status`,a.`freeze`,a.`orderid`,b.`status` as order_status,b.`price` as order_price,b.`uid` as order_uid FROM `".DB::table("paipai_goods")."` AS a LEFT JOIN `".DB::table('paipai_buy')."` AS b ON a.`orderid`=b.`orderid` WHERE a.`tid` =".$tid;
		$query = DB::query($sql);
		$row = db_get_one($query);

		return $row  ? $row : null;
	}
	/**
	 * [getgoods_maxbuy_by_tid 根据tid获得该商品最高出价对应出价信息]
	 * @param  [type] $tid [description]
	 * @return [type]      [description]
	 */
	public function getgoods_maxbuy_by_tid($tid){
		$query = DB::query("SELECT * FROM `".DB::table('paipai_buy')."` WHERE `tid`='$tid'  ORDER BY `price` DESC, `time` DESC LIMIT 1");
		
		$row = db_get_one($query);

		return $row  ? $row : null;
	}
	/**
	 * [getorderdetail 根据tid获得出价信息]
	 * @param  [type] $tid [description]
	 * @return [type]      [description]
	 */
	public function getorderdetail($tid) {
		$query = DB::query("SELECT * FROM `".DB::table("paipai_buy")."` WHERE `tid` = '$tid' ORDER BY `price` ASC");
		return db_get_array($query);
	}
	
	/**
	 * [getorderdetail_by_orderid 根据订单id获得订单信息]
	 * @param  [type] $orderid [description]
	 * @return [type]          [description]
	 */
	public function getorderdetail_by_orderid($orderid) {
		$query = DB::query("SELECT * FROM `".DB::table("paipai_buy")."` WHERE `orderid` = '$orderid' ORDER BY `price` DESC");
		return db_get_one($query);
	}

	/**
	 * [getgoodsdetail_by_tid 根据tid获得商品信息]
	 * @param  [type] $tid [description]
	 * @return [type]      [description]
	 */
	public function getgoodsdetail_by_tid($tid) {
		$query = DB::query("SELECT * FROM `".DB::table("paipai_goods")."` WHERE `tid` = '$tid'");
		$array = db_get_one($query);

		$time = time();
		if($array['date_end'] < $time){
			$array['str'] = '出价结束';
		}elseif($array['date_start'] > $time){//交易开始时间大于当前时间
			// $left_time = get_left_time($v['date_start'] - $time,0);//获得剩余时间字符串表示,不显示秒数
			$array['str'] = '<div style="font-size:18px;marin-top:10px;font-weight:400;">距离拍卖开始还有:<span class="show_time" start="'.$time.'" end="'.$array['date_start'].'"></span></div>';
		}elseif($array['date_end'] > $time){//拍卖进行中
			// $left_time = get_left_time($v['date_end'] - $time);
			$array['str'] = '<div style="font-size:18px;marin-top:10px;font-weight:400;">拍卖进行中，剩余时间:<span class="show_time" start="'.$time.'" end="'.$array['date_end'].'"></span></div>';

		}
		$array['date_start_f'] = date('Y-m-d H:i',$array['date_start']);
		$array['date_end_f'] = date('Y-m-d H:i',$array['date_end']);

		
		return $array;
	}

	/**
	 * [getgoodsdetail 根据gid获得商品信息]
	 * @param  [type] $gid [description]
	 * @return [type]      [description]
	 */
	public function getgoodsdetail($gid) {
		$query = DB::query("SELECT * FROM `".DB::table("paipai_goods")."` WHERE `gid` = '$gid'");
		$array = db_get_one($query);
		return $array ? $array : array();
	}
	
	/**
	 * [check_is_freeze 检测是否冻结]
	 * @param  [type] $tid [description]
	 * @return [Boolean]      [商品是否冻结]
	 */
	public function check_is_freeze($tid){
		$query = DB::query("SELECT * FROM `".DB::table('paipai_goods')."` WHERE `freeze` = 1 AND `tid` = '".$tid."'");
		$row = db_get_one($query);
		if($row){
			return false;
		}
		return true;
	}
	/**
	 * [check_goods_status 检测商品状态 是否为冻结]
	 * @param  [type]  $tid     [description]
	 * @param  string  $type    [是否显示文字提示]
	 * @param  boolean $admincp [允许管理用户查看]
	 * @return [type]           [description]
	 */
	public function check_goods_status($tid,$type = 'message',$admincp = FALSE) {
		global $_G;
		global $admingroup;

		if($admincp) {
			if($_G['groupid'] == $admingroup) {
				return true;
			}
		}
		
		$info = $this->get_goods_buy_order_by_tid($tid);

		// $query = DB::query("SELECT * FROM `".DB::table('paipai_goods')."` WHERE `freeze` = 1 AND `tid` = '".$tid."'");
		
		if($info['freeze'] ){
			if($type == 'message'  && $info['uid'] != $_G['uid'] && $_G['uid'] != $info['order_uid']) {
				showmessage("对不起，当前交易已被冻结");
			} else {
				return false;
			}
			

		}else{
			return true;
		}


		
	
	}
	
	/**
	 * [get_thread_type 获得所有商品拍卖模式]
	 * @param  boolean $FILENAME [description]
	 * @return [type]            [description]
	 */
	public function get_thread_type($FILENAME = FALSE) { //获取当前安装扩展的文件
		global $DISCUZ_PAIPAI_VERSION;
		if($FILENAME) {
			if($FILENAME == 'default' || $FILENAME == '') {
				return "默认模式";
			}
			if(file_exists("./source/plugin/iweitao_paipai/$FILENAME/index.php")){
				require_once "./source/plugin/iweitao_paipai/$FILENAME/index.php";
				// $pluginname = "定金拍卖";
				return $pluginname;
			} else {
				showmessage("扩展模块不存在，请联系管理员");
			}
		} else {
			//默认模式扩展模块 1.delay->延时拍卖    2.(tenpay->定金拍卖)
			$types = array('delay','tenpay');
			$loop = array();

			foreach($types as $filename){
				if(!file_exists("./source/plugin/iweitao_paipai/$filename/index.php")){
					showmessage("扩展模块不存在，请联系管理员");
				}
				require_once "./source/plugin/iweitao_paipai/$filename/index.php";
				$loop[$filename] = $type;
			}
			

			return $loop;
			
		}
	
	}
	
	private function getapihook($hookname) {
		global $DISCUZ_PAIPAI_VERSION;
		if($hookname == '') {
			return false;
		}
		
		$files = array('js','template','image','.','..'); //定义公用目录
		$handler = opendir("./source/plugin/iweitao_paipai/");
		while (($filename = readdir($handler)) !== false) { 
			if(!in_array($filename,$files)) {
				if(!is_dir("./source/plugin/iweitao_paipai/".$filename)) {
					continue;
				}
				if(!file_exists("./source/plugin/iweitao_paipai/$filename/index.php")){
					showmessage("扩展模块不存在，请联系管理员");
				}
				require_once "./source/plugin/iweitao_paipai/$filename/index.php";
				if($type != 'API') { //判断钩子类型
					continue;
				}
				if($version_need > $DISCUZ_PAIPAI_VERSION) { //判断当前版本是否支持改钩子
					continue;
				}
				foreach($load_files as $k => $v) {
					if($k == $hookname) {
						$loadingfiles[] = $loadpath.$v;
					}
				}
			}
		}
		return $loadingfiles;
	}

/**
	 * [get_deal_orders_width_buy 显示交易成功商品及其购买者]
	 * @return [array] [description]
	 */
	public function get_deal_orders_width_buy($where= '',$limit = ''){
		$where = $where ? ' where ' . $where : '';
		$limit = $limit ? ' limit ' . $limit : '';
		$sql = "SELECT a.`uid`,a.`tid`,a.`username`,a.`gid`,a.`title`,a.`date_start`,a.`date_end`,a.`price`,a.`origin_price`,a.`identify`,a.`status`,a.`freeze`,a.`orderid`,b.`status` as order_status,a.`focus`,b.`price` as order_price,b.`uid` as order_uid FROM `".DB::table("paipai_goods")."` AS a LEFT JOIN `".DB::table('paipai_buy')."` AS b ON a.`orderid`=b.`orderid` " . $where . " order by a.pub_time desc " . $limit;
		$query = DB::query($sql);

		$row = db_get_array($query);
		return $row  ? $row : null;
	}


}
?>